package hcj;

import java.sql.Date;
import java.io.IOException;
import java.io.PrintWriter;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SaveUser extends HttpServlet {

	private static final DatastoreService datastore = DatastoreServiceFactory
			.getDatastoreService();

	final FetchOptions fetch_options = FetchOptions.Builder.withPrefetchSize(
			100).chunkSize(100);

	private static final long serialVersionUID = 5346853376006966976L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String[] temp;
		temp = (request.getServletPath() + request.getPathInfo()).split("/");
		if (temp[temp.length - 1].equalsIgnoreCase("SaveUser")) {

			Entity user = new Entity("User");
			user.setProperty("FirstName", request.getParameter("FirstName"));
			user.setProperty("LastName", request.getParameter("LastName"));
			user.setProperty("Date", Date.valueOf(request.getParameter("Date"))
					.toString());
			user.setProperty("City", request.getParameter("City"));

			datastore.put(user);
		} else {
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.println(buildjson(request.getParameter("callback")));
			out.close();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	private String buildjson(String callback) {
		Query q = new Query("User");
		PreparedQuery pq = datastore.prepare(q);
		StringBuffer sb = new StringBuffer(callback);
		sb.append("({\"sEcho\":1,\"iTotalRecords\":\"");
		sb.append(pq.countEntities(fetch_options));
		sb.append("\",\"iTotalDisplayRecords\":\"");
		sb.append(pq.countEntities(fetch_options));
		sb.append("\",\"aaData\":[");
		for (Entity result : pq.asIterable(fetch_options)) {
			sb.append("[\"" + (String) result.getProperty("FirstName") + "\",");
			sb.append('"' + (String) result.getProperty("LastName") + "\",");
			sb.append('"' + (String) result.getProperty("City") + "\",");
			sb.append('"' + (String) result.getProperty("Date") + "\"],");
		}
		if (pq.countEntities(fetch_options) > 0)
			sb.deleteCharAt(sb.length() - 1);
		sb.append("]});");
		return sb.toString();

	}

}
